/*
 * ContainerLoadingView.java
 */

package org.jgap.ga.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.jgap.ga.service.Container;
import org.jgap.ga.constant.Parameter;
import org.jgap.ga.service.ExecuteGA;
import org.jgap.ga.utility.Utility;
import org.jgap.InvalidConfigurationException;
import javax.swing.Timer;
import javax.swing.filechooser.FileFilter;
import org.jgap.ga.constant.Constant;
import org.jgap.ga.exception.GAException;
import org.jgap.ga.model.Ship;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jgap.IChromosome;
import org.jgap.impl.IntegerGene;
import org.apache.log4j.Logger;
/**
 * The application's main frame.
 */
public class ContainerLoadingView extends FrameView {
    private List<Container> containerList=new ArrayList();
    private ExecuteGA executeGA;
    //private XYSeries dataSet;
    private XYSeriesCollection dataSet;
    private XYSeries fitnessSeries;
    private XYSeries avgSeries;
    private Timer t;
    private static Logger logger=Logger.getLogger(ContainerLoadingView.class);
    public ContainerLoadingView(SingleFrameApplication app) {
        super(app);
        initComponents();
        jFittestValue.setText(null);
        jUniformWeight.setText(null);
        jAverageWeight.setText(null);
        //messageTimer=null;
        //busyIconTimer=null;
        //idleIcon=null;
 
        t=new Timer(1000,new ActionListener(){
            public void actionPerformed(ActionEvent e){
                DoEvolutions();
            }
        });
        
    }

  

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jGAPanel = new javax.swing.JPanel();
        jEvolutionsLabel = new javax.swing.JLabel();
        jEvolution = new javax.swing.JTextField();
        jEvovle = new javax.swing.JButton();
        jFittestValueLabel = new javax.swing.JLabel();
        jFittestValue = new javax.swing.JLabel();
        jAverageWeight = new javax.swing.JLabel();
        jUniformWeightLabel = new javax.swing.JLabel();
        jPopulationLabel = new javax.swing.JLabel();
        jFitnessFunction = new javax.swing.JLabel();
        jPopulation = new javax.swing.JTextField();
        jFitnessNormal = new javax.swing.JRadioButton();
        jFitnessSquare = new javax.swing.JRadioButton();
        jFitnessLog = new javax.swing.JRadioButton();
        jAverageWeightLabel = new javax.swing.JLabel();
        jUniformWeight = new javax.swing.JLabel();
        jStopButton = new javax.swing.JButton();
        jClear = new javax.swing.JButton();
        jContainerSetupPanel = new javax.swing.JPanel();
        jLevelNo = new javax.swing.JTextField();
        jContainerNoLabel = new javax.swing.JLabel();
        jContainerNo = new javax.swing.JTextField();
        jLevelNoLabel = new javax.swing.JLabel();
        jGenerateData = new javax.swing.JButton();
        jLoadExcel = new javax.swing.JButton();
        jChartPanel = new javax.swing.JPanel();
        jContainerPanel = new javax.swing.JPanel();
        jContainerScroll = new javax.swing.JScrollPane();
        jContainerTable = new javax.swing.JTable();
        jClearTable = new javax.swing.JButton();
        buttonGroup1 = new javax.swing.ButtonGroup();

        mainPanel.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        mainPanel.setName("mainPanel"); // NOI18N

        jGAPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "GA Setup", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12), null)); // NOI18N
        jGAPanel.setName("jGASetupPanel"); // NOI18N

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jgap/ga/gui/resources/ContainerLoadingView"); // NOI18N
        jEvolutionsLabel.setText(bundle.getString("jEvolutionsLabel")); // NOI18N
        jEvolutionsLabel.setName("jEvolutionsLabel"); // NOI18N

        jEvolution.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        jEvolution.setText(bundle.getString("jEvolution.text")); // NOI18N
        jEvolution.setName("jEvolution"); // NOI18N

        jEvovle.setText(bundle.getString("jEvovle.text")); // NOI18N
        jEvovle.setName("jEvovle"); // NOI18N
        jEvovle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jEvovleActionPerformed(evt);
            }
        });

        jFittestValueLabel.setText(bundle.getString("jFittestValueLabel.text")); // NOI18N
        jFittestValueLabel.setName("jFittestValueLabel"); // NOI18N

        jFittestValue.setName("jFittestValue"); // NOI18N

        jAverageWeight.setName("jAverageWeight"); // NOI18N

        jUniformWeightLabel.setText(bundle.getString("jUniformWeightLabel.text")); // NOI18N
        jUniformWeightLabel.setName("jUniformWeightLabel"); // NOI18N

        jPopulationLabel.setText(bundle.getString("jPopulationLabel.text")); // NOI18N
        jPopulationLabel.setName("jPopulationLabel"); // NOI18N

        jFitnessFunction.setText(bundle.getString("jFitnessFunction.text")); // NOI18N
        jFitnessFunction.setName("jFitnessFunction"); // NOI18N

        jPopulation.setText(bundle.getString("jPopulation.text")); // NOI18N
        jPopulation.setName("jPopulation"); // NOI18N

        buttonGroup1.add(jFitnessNormal);
        jFitnessNormal.setText(bundle.getString("jFitnessNormal.text")); // NOI18N
        jFitnessNormal.setName("jFitnessNormal"); // NOI18N

        buttonGroup1.add(jFitnessSquare);
        jFitnessSquare.setSelected(true);
        jFitnessSquare.setText(bundle.getString("jFitnessSquare.text")); // NOI18N
        jFitnessSquare.setName("jFitnessSquare"); // NOI18N

        buttonGroup1.add(jFitnessLog);
        jFitnessLog.setText(bundle.getString("jFitnessLog.text")); // NOI18N
        jFitnessLog.setName("jFitnessLog"); // NOI18N

        jAverageWeightLabel.setText(bundle.getString("jAverageWeightLabel.text")); // NOI18N
        jAverageWeightLabel.setName("jAverageWeightLabel"); // NOI18N

        jUniformWeight.setName("jUniformWeight"); // NOI18N

        jStopButton.setText(bundle.getString("jStopButton.text")); // NOI18N
        jStopButton.setName("jStopButton"); // NOI18N
        jStopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jStopButtonActionPerformed(evt);
            }
        });

        jClear.setText(bundle.getString("jClear.text")); // NOI18N
        jClear.setName("jClear"); // NOI18N
        jClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jClearActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jGAPanelLayout = new org.jdesktop.layout.GroupLayout(jGAPanel);
        jGAPanel.setLayout(jGAPanelLayout);
        jGAPanelLayout.setHorizontalGroup(
            jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jGAPanelLayout.createSequentialGroup()
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jEvolutionsLabel)
                    .add(jPopulationLabel)
                    .add(jUniformWeightLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 132, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jFittestValueLabel)
                    .add(jAverageWeightLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jGAPanelLayout.createSequentialGroup()
                        .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                    .add(jPopulation)
                                    .add(jEvolution, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(jFittestValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 127, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(jAverageWeight, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(jClear))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jFitnessNormal)
                            .add(jFitnessFunction)
                            .add(jFitnessLog)
                            .add(jFitnessSquare)
                            .add(jGAPanelLayout.createSequentialGroup()
                                .add(jEvovle)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(jStopButton))))
                    .add(jUniformWeight, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 106, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(70, Short.MAX_VALUE))
        );
        jGAPanelLayout.setVerticalGroup(
            jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jGAPanelLayout.createSequentialGroup()
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jEvolutionsLabel)
                    .add(jEvolution, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jFitnessFunction))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jPopulationLabel)
                    .add(jPopulation, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jFitnessNormal, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jGAPanelLayout.createSequentialGroup()
                        .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jFittestValueLabel)
                            .add(jFittestValue))
                        .add(11, 11, 11))
                    .add(jGAPanelLayout.createSequentialGroup()
                        .add(jFitnessSquare)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)))
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jAverageWeightLabel)
                        .add(jFitnessLog))
                    .add(jAverageWeight))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jUniformWeightLabel)
                    .add(jUniformWeight, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(38, 38, 38))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jGAPanelLayout.createSequentialGroup()
                .addContainerGap(152, Short.MAX_VALUE)
                .add(jGAPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jEvovle)
                    .add(jStopButton)
                    .add(jClear))
                .addContainerGap())
        );

        jContainerSetupPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Container Setup", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12), null)); // NOI18N
        jContainerSetupPanel.setName("jContainer"); // NOI18N

        jLevelNo.setName("jLevelNo"); // NOI18N

        jContainerNoLabel.setText(bundle.getString("jContainerNoLabel.text")); // NOI18N
        jContainerNoLabel.setName("jContainerNoLabel"); // NOI18N

        jContainerNo.setName("jContainerNo"); // NOI18N

        jLevelNoLabel.setText(bundle.getString("jLevelNoLabel.text")); // NOI18N
        jLevelNoLabel.setName("jLevelNoLabel"); // NOI18N

        jGenerateData.setText(bundle.getString("jGenerateData.text")); // NOI18N
        jGenerateData.setName("jGenerateData"); // NOI18N
        jGenerateData.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jGenerateDataActionPerformed(evt);
            }
        });

        jLoadExcel.setText(bundle.getString("jLoadExcel.text")); // NOI18N
        jLoadExcel.setName("jLoadExcel"); // NOI18N
        jLoadExcel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jLoadExcelActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jContainerSetupPanelLayout = new org.jdesktop.layout.GroupLayout(jContainerSetupPanel);
        jContainerSetupPanel.setLayout(jContainerSetupPanelLayout);
        jContainerSetupPanelLayout.setHorizontalGroup(
            jContainerSetupPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jContainerSetupPanelLayout.createSequentialGroup()
                .add(jContainerNoLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jContainerNo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 31, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jLevelNoLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLevelNo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(26, 26, 26)
                .add(jGenerateData)
                .add(18, 18, 18)
                .add(jLoadExcel)
                .addContainerGap(262, Short.MAX_VALUE))
        );
        jContainerSetupPanelLayout.setVerticalGroup(
            jContainerSetupPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jContainerSetupPanelLayout.createSequentialGroup()
                .add(jContainerSetupPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jContainerNoLabel)
                    .add(jContainerNo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLevelNoLabel)
                    .add(jGenerateData)
                    .add(jLoadExcel)
                    .add(jLevelNo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jChartPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Chart", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12), null)); // NOI18N
        jChartPanel.setMaximumSize(new java.awt.Dimension(100, 100));
        jChartPanel.setName("jChartPanel"); // NOI18N

        org.jdesktop.layout.GroupLayout jChartPanelLayout = new org.jdesktop.layout.GroupLayout(jChartPanel);
        jChartPanel.setLayout(jChartPanelLayout);
        jChartPanelLayout.setHorizontalGroup(
            jChartPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 366, Short.MAX_VALUE)
        );
        jChartPanelLayout.setVerticalGroup(
            jChartPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 749, Short.MAX_VALUE)
        );

        jContainerPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Container Data", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12), null)); // NOI18N
        jContainerPanel.setName("jContainerPanel"); // NOI18N

        jContainerScroll.setName("jContainerScroll"); // NOI18N

        jContainerTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Location ID", "Container ID", "Weight", "Port ID", "Flammable Index"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jContainerTable.setName("jContainerTable"); // NOI18N
        jContainerScroll.setViewportView(jContainerTable);
        jContainerTable.getColumnModel().getColumn(3).setMaxWidth(50);

        jClearTable.setText(bundle.getString("jClearTable.text")); // NOI18N
        jClearTable.setName("jClearTable"); // NOI18N
        jClearTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jClearTableActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jContainerPanelLayout = new org.jdesktop.layout.GroupLayout(jContainerPanel);
        jContainerPanel.setLayout(jContainerPanelLayout);
        jContainerPanelLayout.setHorizontalGroup(
            jContainerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jContainerPanelLayout.createSequentialGroup()
                .add(jContainerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jContainerPanelLayout.createSequentialGroup()
                        .add(130, 130, 130)
                        .add(jClearTable))
                    .add(jContainerScroll, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 726, Short.MAX_VALUE))
                .addContainerGap())
        );
        jContainerPanelLayout.setVerticalGroup(
            jContainerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jContainerPanelLayout.createSequentialGroup()
                .add(jContainerScroll, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(jClearTable)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jContainerPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jContainerSetupPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jGAPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jChartPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jChartPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup()
                        .add(jGAPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jContainerSetupPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jContainerPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );

        setComponent(mainPanel);
    }// </editor-fold>//GEN-END:initComponents

private void jEvovleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jEvovleActionPerformed

    if(ValidateContainer() && ValidateGA()){
        DefaultTableModel tableModel = (DefaultTableModel) jContainerTable.getModel();
        List<Container> dataList = new ArrayList();
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            Container container = new Container();
            container.setContainerId((Integer) tableModel.getValueAt(i, 1));
            container.setWeight((Double) tableModel.getValueAt(i, 2));
            container.setPort((Integer) tableModel.getValueAt(i, 3));
            container.setFlammableindex((Double) tableModel.getValueAt(i, 4));
            dataList.add(container);
        }
        this.containerList.clear();
        this.containerList.addAll(dataList);
        try{
            if (buttonGroup1.isSelected(jFitnessNormal.getModel())) {
                executeGA = new ExecuteGA(Integer.parseInt(jEvolution.getText()), this.containerList, Constant.FITNESS_FUNC_NORMAL);
            } else if (buttonGroup1.isSelected(jFitnessSquare.getModel())) {
                executeGA = new ExecuteGA(Integer.parseInt(jEvolution.getText()), this.containerList, Constant.FITNESS_FUNC_SQUARE);
            } else if (buttonGroup1.isSelected(jFitnessLog.getModel())) {
                executeGA = new ExecuteGA(Integer.parseInt(jEvolution.getText()), this.containerList, Constant.FITNESS_FUNC_LOG);
            }
        }catch(InvalidConfigurationException ex){
            DisplayMessage(ex.getMessage(), JOptionPane.ERROR_MESSAGE);
        }
        if (this.dataSet != null) {
            avgSeries.clear();
            fitnessSeries.clear();
            DisplayChart();
        }
        t.start();
        EnableDisableButtons(false);
    }
    
}//GEN-LAST:event_jEvovleActionPerformed

private void jGenerateDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jGenerateDataActionPerformed
    if(ValidateContainer()){
        List<Container> dataList = Utility.CreateContainerList();
        List<Object[]> list = new ArrayList();
        for (int i = 0; i < dataList.size(); i++) {
            Container container = dataList.get(i);
            Object[] data = new Object[5];
            data[0] = i;
            data[1] = container.getContainerId();
            data[2] = container.getWeight();
            data[3] = container.getPort();
            data[4] = container.getFlammableindex();
            list.add(data);
        }
        PopulateTable(list);
    }
}//GEN-LAST:event_jGenerateDataActionPerformed

private void jLoadExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLoadExcelActionPerformed
    JFileChooser openExcel=new JFileChooser();
     openExcel.setAcceptAllFileFilterUsed(false);
     openExcel.setMultiSelectionEnabled(false);
     openExcel.setFileSelectionMode(JFileChooser.FILES_ONLY);
     openExcel.setDialogTitle("Load Excel File");
     openExcel.setCurrentDirectory(new File(System.getProperty("user.dir")));
     FileFilter filter = new ExtensionFileFilter("Excel Files", new String[] {"xls"});
     openExcel.setFileFilter(filter);
     int returnVal = openExcel.showOpenDialog(ContainerLoadingApp.getApplication().getMainFrame());      
     if(returnVal==JFileChooser.APPROVE_OPTION){
         File selectedFile=openExcel.getSelectedFile();
         LoadExcel(selectedFile);
     }       
    
}//GEN-LAST:event_jLoadExcelActionPerformed

private void jClearTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jClearTableActionPerformed
    DefaultTableModel tablemodel=(DefaultTableModel)jContainerTable.getModel();
    if(tablemodel.getRowCount()!=0){
        int ret=DisplayAlert("Are you sure you want to clear the table",JOptionPane.YES_NO_OPTION);
        if(ret==JOptionPane.YES_OPTION){
            jContainerNo.setEnabled(true);
            while(tablemodel.getRowCount()!=0){
                tablemodel.removeRow(0);
            }
        }
    }
}//GEN-LAST:event_jClearTableActionPerformed

private void jStopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jStopButtonActionPerformed
    t.stop();
    int ret=DisplayAlert("Are you sure you want to stop", JOptionPane.YES_NO_OPTION);
    if(ret==JOptionPane.YES_OPTION){
        t.stop();
        EnableDisableButtons(true);
    }else{
        t.start();
    }
    
}//GEN-LAST:event_jStopButtonActionPerformed

private void jClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jClearActionPerformed
    jPopulation.setText("50");
    jEvolution.setText("100");
    jAverageWeight.setText(null);
    jUniformWeight.setText(null);
    jFittestValue.setText(null);
    if(this.dataSet!=null){
        avgSeries.clear();
        fitnessSeries.clear();
    }
    jChartPanel.removeAll();
    jChartPanel.updateUI();
}//GEN-LAST:event_jClearActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jAverageWeight;
    private javax.swing.JLabel jAverageWeightLabel;
    private javax.swing.JPanel jChartPanel;
    private javax.swing.JButton jClear;
    private javax.swing.JButton jClearTable;
    private javax.swing.JTextField jContainerNo;
    private javax.swing.JLabel jContainerNoLabel;
    private javax.swing.JPanel jContainerPanel;
    private javax.swing.JScrollPane jContainerScroll;
    private javax.swing.JPanel jContainerSetupPanel;
    private javax.swing.JTable jContainerTable;
    private javax.swing.JTextField jEvolution;
    private javax.swing.JLabel jEvolutionsLabel;
    private javax.swing.JButton jEvovle;
    private javax.swing.JLabel jFitnessFunction;
    private javax.swing.JRadioButton jFitnessLog;
    private javax.swing.JRadioButton jFitnessNormal;
    private javax.swing.JRadioButton jFitnessSquare;
    private javax.swing.JLabel jFittestValue;
    private javax.swing.JLabel jFittestValueLabel;
    private javax.swing.JPanel jGAPanel;
    private javax.swing.JButton jGenerateData;
    private javax.swing.JTextField jLevelNo;
    private javax.swing.JLabel jLevelNoLabel;
    private javax.swing.JButton jLoadExcel;
    private javax.swing.JTextField jPopulation;
    private javax.swing.JLabel jPopulationLabel;
    private javax.swing.JButton jStopButton;
    private javax.swing.JLabel jUniformWeight;
    private javax.swing.JLabel jUniformWeightLabel;
    private javax.swing.JPanel mainPanel;
    // End of variables declaration//GEN-END:variables

    /*private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    */
    
    private void DoEvolutions(){
        try{
            t.stop();
            executeGA.RunEvolution();
            jEvolution.setText(Integer.toString(executeGA.GetEvolutionRemaining()+1));
            UpdateStatus();
            t.start();
        }catch(GAException ex){
            JOptionPane.showMessageDialog(ContainerLoadingApp.getApplication().getMainFrame(), ex.getMessage(), "GA",JOptionPane.INFORMATION_MESSAGE);
            t.stop();
            EnableDisableButtons(true);
        }
    }
    
    private void UpdateStatus(){
        jFittestValue.setText(Double.toString(Utility.round(executeGA.GetFitnessValue(),2)));
        jAverageWeight.setText(Double.toString(Utility.round(executeGA.getAverageWeight(),2)));
        jUniformWeight.setText(Double.toString(Utility.round(executeGA.getUnformWeight(),2)));
        UpdateDataSet(executeGA.GetEvolutionCompleted(),executeGA.GetFitnessValue(),executeGA.GetAverageFittestValue());
        DefaultTableModel tablemodel=(DefaultTableModel)jContainerTable.getModel();
     
        IChromosome chromosome=executeGA.GetFittestChromosome();
         
         for(int i=0; i<chromosome.size();i++){
             IntegerGene containerGene=(IntegerGene)chromosome.getGene(i);
             int containerId=containerGene.intValue();
             Container container=this.containerList.get(containerId);
                tablemodel.setValueAt(container.getContainerId(), i, 1);
                tablemodel.setValueAt(container.getWeight(), i, 2);
                tablemodel.setValueAt(container.getPort(), i, 3);
                
         }


     }    
    
  private  class ExtensionFileFilter extends FileFilter {
  String description;

  String extensions[];

  public ExtensionFileFilter(String description, String extension) {
    this(description, new String[] { extension });
  }

  public ExtensionFileFilter(String description, String extensions[]) {
    if (description == null) {
      this.description = extensions[0];
    } else {
      this.description = description;
    }
    this.extensions = (String[]) extensions.clone();
    toLower(this.extensions);
  }

  private void toLower(String array[]) {
    for (int i = 0, n = array.length; i < n; i++) {
      array[i] = array[i].toLowerCase();
    }
  }
  
  @Override
  public String getDescription() {
    return description;
  }

  @Override
  public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
          return true;
        }
      }
    }
    return false;
  }
}
  
  public void LoadExcel(File file){
      
    try{
          HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(file));
          HSSFSheet sheet=workbook.getSheetAt(0);
          List<Object[]> list=new ArrayList();

          for(Iterator rowIterator = sheet.rowIterator();rowIterator.hasNext();){
              HSSFRow row=(HSSFRow)rowIterator.next();
              if(row.getRowNum()!=0){
                  Object[] data=new Object[5];
                  data[0]=row.getRowNum()-1;
                  data[1]=(int)row.getCell((short)0).getNumericCellValue();
                  data[2]=Utility.round(row.getCell((short)1).getNumericCellValue(),2);
                  data[3]=(int)row.getCell((short)2).getNumericCellValue();
                  data[4]=Utility.round(row.getCell((short)3).getNumericCellValue(),1);
                  list.add(data);
              }
          }
        jContainerNo.setEnabled(false);  
        jContainerNo.setText(Integer.toString(list.size()));  
        PopulateTable(list);
    }catch(Exception ex){
        if(ex.getMessage()!=null){
            DisplayMessage(ex.getMessage(),JOptionPane.ERROR_MESSAGE);
        }else{
            DisplayMessage("Error in reading the Excel File, Please Check the Data",JOptionPane.ERROR_MESSAGE);
        }
    }
  }

  private void PopulateTable(List<Object[]> list){
     DefaultTableModel tablemodel=(DefaultTableModel)jContainerTable.getModel();
     while(tablemodel.getRowCount()!=0){
        tablemodel.removeRow(0);
     }
          
    for(int i=0;i<list.size();i++){   
        tablemodel.addRow(list.get(i));
    }
    jContainerTable.updateUI();
    DisplayData();
  }
  
  private void UpdateDataSet(int evolution,double fitnessvalue,double avgFitness) {
    if(this.dataSet==null){
        //this.dataSet = new XYSeries("Fitness Value");
        dataSet=new XYSeriesCollection();
        fitnessSeries=new XYSeries("Fitness Value");
        avgSeries=new XYSeries("Avg Fitness Value");
        dataSet.addSeries(fitnessSeries);
        dataSet.addSeries(avgSeries);
    }
    
    fitnessSeries.add(evolution, fitnessvalue);
    avgSeries.add(evolution, avgFitness);
    
    
//    this.dataSet.add(evolution,fitnessvalue);
    /*if(dataSet==null){
       dataSet=new DefaultCategoryDataset();
    }
   dataSet.addValue(fitnessvalue, "Fittest Value", Integer.toString(evolution));  
   dataSet.addValue(avgFitness, "Average Fitness Value", Integer.toString(evolution));
   */ 
   DisplayChart();
}
 
  private void DisplayChart(){
    JFreeChart chart = ChartFactory.createXYLineChart("GA Fitness Chart", "Evolutions", "Fitness Value",this.dataSet,PlotOrientation.VERTICAL,true,true,false);
    chart.setBackgroundPaint(new Color(0xCC, 0xCC, 0xFF));
    jChartPanel.removeAll();
    jChartPanel.setPreferredSize(new Dimension(600,700));
    jChartPanel.setLayout(new BorderLayout());
    jChartPanel.add(new ChartPanel(chart), BorderLayout.CENTER);
    jChartPanel.updateUI();
  }
  
  private void DisplayMessage(String message,int type){
      JOptionPane.showMessageDialog(ContainerLoadingApp.getApplication().getMainFrame(), message, "Container Loading",type);
  }
  
  private int DisplayAlert(String message,int type){
      return JOptionPane.showOptionDialog(ContainerLoadingApp.getApplication().getMainFrame(),message, "Container Loading",type,JOptionPane.QUESTION_MESSAGE,null,null,null);
  }
  
  private boolean ValidateContainer(){
      
    if (jContainerNo.getText() == null || jContainerNo.getText().trim().equals("")) {
        DisplayMessage("Please Enter the Container No", JOptionPane.ERROR_MESSAGE);
        jContainerNo.requestFocusInWindow();
        return false;
    }

    if (jLevelNo.getText() == null || jLevelNo.getText().trim().equals("")) {
        DisplayMessage("Please Enter the Level No", JOptionPane.ERROR_MESSAGE);
        jLevelNo.requestFocusInWindow();
        return false;
    }
    try {
        Parameter.CONTAINER_NO = Integer.parseInt(jContainerNo.getText());
        if(Parameter.CONTAINER_NO<=0){
            DisplayMessage("Please Enter value greater than 0 for Container No", JOptionPane.ERROR_MESSAGE);
            jContainerNo.setText(null);
            jContainerNo.requestFocusInWindow();
            return false;
        }
        try {
            Parameter.LEVEL_NO = Integer.parseInt(jLevelNo.getText());
            if(Parameter.LEVEL_NO<=0){
                DisplayMessage("Please Enter value greater than 0 for Level No", JOptionPane.ERROR_MESSAGE);
                jLevelNo.setText(null);
                jLevelNo.requestFocusInWindow();
                return false;
            }
            // esnure that it is evenly divisible
            if (Parameter.CONTAINER_NO % Parameter.LEVEL_NO != 0) {
                DisplayMessage("The Container No must be evenly divisble by Level No", JOptionPane.ERROR_MESSAGE);
                return false;
            } 
            return true;
        } catch (NumberFormatException ex) {
            jLevelNo.setText(null);
            jLevelNo.requestFocusInWindow();
            DisplayMessage("Please enter numeric value for Level No", JOptionPane.ERROR_MESSAGE);
        }
    } catch (NumberFormatException ex) {
        jContainerNo.setText(null);
        jContainerNo.requestFocusInWindow();
        DisplayMessage("Please enter numeric value for Container No", JOptionPane.ERROR_MESSAGE);
    }
      return false;
  }
  
  private boolean ValidateGA(){
    if (jPopulation.getText() == null || jPopulation.getText().trim().equals("")) {
        DisplayMessage("Please Enter the Population Size", JOptionPane.ERROR_MESSAGE);
        jPopulation.requestFocusInWindow();
        return false;
    }

    if (jEvolution.getText() == null || jEvolution.getText().trim().equals("")) {
        DisplayMessage("Please Enter the Evolution No", JOptionPane.ERROR_MESSAGE);
        jEvolution.requestFocusInWindow();
        return false;
    }
    try {
        Parameter.POPULATION_SIZE = Integer.parseInt(jPopulation.getText());
        if(Parameter.POPULATION_SIZE<=0){
            DisplayMessage("Please Enter value greater than 0 for Population Size", JOptionPane.ERROR_MESSAGE);
            jPopulation.setText(null);
            jPopulation.requestFocusInWindow();
            return false;
        }
        try {
            int evolution = Integer.parseInt(jEvolution.getText());
            if(evolution<=0){
                DisplayMessage("Please Enter value greater than 0 for Evolution", JOptionPane.ERROR_MESSAGE);
                jEvolution.setText(null);
                jEvolution.requestFocusInWindow();
                return false;
            }
            DefaultTableModel tableModel = (DefaultTableModel) jContainerTable.getModel();
            if (tableModel.getRowCount() == 0) {
                DisplayMessage("Please Populate Data into the table", JOptionPane.ERROR_MESSAGE);
                return false;
            } 
            return true;
        } catch (NumberFormatException ex) {
            jEvolution.setText(null);
            jEvolution.requestFocusInWindow();
            DisplayMessage("Please enter numeric value for Evolution No", JOptionPane.ERROR_MESSAGE);
        }
    } catch (NumberFormatException ex) {
        jPopulation.setText(null);
        jPopulation.requestFocusInWindow();
        DisplayMessage("Please enter numeric value for Population size", JOptionPane.ERROR_MESSAGE);
    }
      return false;
      
  }
  
  private void EnableDisableButtons(boolean enable){
      jClear.setEnabled(enable);
      jGenerateData.setEnabled(enable);
      jLoadExcel.setEnabled(enable);
      jClearTable.setEnabled(enable);
      jPopulation.setEnabled(enable);
      jEvolution.setEnabled(enable);
      jContainerNo.setEnabled(enable);
      jLevelNo.setEnabled(enable);
  }
  
  private void DisplayData(){
        jAverageWeight.setText(null);
        jUniformWeight.setText(null);
        DefaultTableModel tableModel = (DefaultTableModel) jContainerTable.getModel();
        List<Container> dataList = new ArrayList();
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            Container container = new Container();
            container.setContainerId((Integer) tableModel.getValueAt(i, 1));
            container.setWeight((Double) tableModel.getValueAt(i, 2));
            container.setPort((Integer) tableModel.getValueAt(i, 3));
            container.setFlammableindex((Double) tableModel.getValueAt(i, 4));
            dataList.add(container);
        }

        Ship ship=new Ship();
        ship.LoadShip(dataList);
        double uniformWeight=0.0d;
        jAverageWeight.setText(Double.toString(Utility.round(ship.GetAverageWeight(),2)));
         if (buttonGroup1.isSelected(jFitnessNormal.getModel())) {
            uniformWeight= ship.CalculateWeightFitness();
         } else if (buttonGroup1.isSelected(jFitnessSquare.getModel())) {
            uniformWeight= ship.CalculateWeightFitnessSquare();
         } else if (buttonGroup1.isSelected(jFitnessLog.getModel())) {
            uniformWeight= ship.CalculateWeightFitnessLogarithm();
         }
        jUniformWeight.setText(Double.toString(Utility.round(uniformWeight,2)));
  }
}
